package job.manager.security.app;

import job.manager.security.interfaces.AppUserInt;
import job.manager.security.interfaces.UserDataConnectorInt;
import org.springframework.dao.DataAccessException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;

/**
 *  Habdles the request to login a user and collects it from the Database and creates
 *  a application user to be checked by spring security
 *
 */
public class UDService implements UserDetailsService {

    private UserDataConnectorInt udConn;

    public UDService(UserDataConnectorInt udConn) {
        this.udConn = udConn;
    }

    //load the user from the database
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException, DataAccessException {
        AppUserInt user = udConn.findUser(username);
        if (user == null)
            throw new UsernameNotFoundException("User not found: " + username);
        else {
            return makeUser(user);
        }
    }

    //creates the user that spring security uses to check if the user got acces to the application
    private org.springframework.security.userdetails.User makeUser(AppUserInt user) {
        return new org.springframework.security.userdetails.User(user.getLogin(), user
                .getPassword(), true, true, true, true,
                makeGrantedAuthorities(user));
    }

    //add's roles to the Application User
    private GrantedAuthority[] makeGrantedAuthorities(AppUserInt user) {
        GrantedAuthority[] result = new GrantedAuthority[user.getRoles().size()];
        int i = 0;
        for (String role : user.getRoles()) {
            result[i++] = new GrantedAuthorityImpl(role);
        }
        return result;
    }

}